<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.Statement" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page language="java" import="java.lang.*" %>
<%@ page import = "java.sql.SQLException" %>
<%@ page import = "com.seniorproject.aims.*" %>
<%@ page import = "java.util.List" %>
<%@ page import = "java.util.ArrayList"%>
<%@ page import = "java.util.Properties" %>
<%@ page import = "javax.servlet.ServletContext" %>
<%@ page import = "java.io.File" %>
<%@ page import = "java.io.InputStream" %>
<%@page import="java.util.regex.Matcher"%>
<%@page import="java.util.regex.Pattern"%>

<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>Account Add</title>
	
	<link rel="stylesheet" type="text/css" href="css/stylev2.css" /> 
	<link rel="stylesheet" type="text/css" href="css/frame.css" />
	
	<script type="text/javascript" src="js/jquery-2.1.1.min.js"></script>
	
	<style type="text/css">
		input {
			font-size: 20px;
		}
		
		select {
			font-size: 20px;
		}
		
		a {
	      text-decoration:none;
	   }
	</style>
	
	<script type="text/javascript">

		//var role_list = new Array();
		var count = 0;
		var checkUsername = true;
	
		
		$(document).ready(function(){
			
			$('#table_role_add').hide();
		
		
			$('#add').click(function(){
				var select = document.getElementById("role");
				var roleId = select.options[select.selectedIndex].value;
				var roleName = select.options[select.selectedIndex].text;
				
				if(roleId == "select") {
					alert("กรุณาเลือกหน้าที่ก่อนค่ะ");
				}
				else {
					var check_roleName = true;
					
					var length = $('#table_role_add tr').length;
					
					//alert("ln : "+length);
					
					if(length > 1) {
						for(var i=1; i<length; i++) {
							var roleName_table = $('#roleName'+i).val();
							
							if(roleName == roleName_table) {
								check_roleName = false;
								break;
							}
						}
					}
					
				/*	for(var i=0; i<role_list.length; i++) {
						if(roleName == role_list[i]) {
							alert(role_list[i]+" เลือกแล้วค่ะ");
							check_roleName = false;
						}
					}
			*/
					if(check_roleName) {

						$('#table_role_add').show();
						
						//role_list.push(roleName);

						count++;
						
						var input = '<input type="hidden" id="roleId_add'+count+'" name="roleId_add'+count+'" value="'+roleId+'" />'
								+ '<input type="hidden" id="roleName'+count+'" name="roleName'+count+'" value="'+roleName+'" />';
						
						$('#table_role_add').append(input);
						
						var text = '<tr id="role_add'+count+'" name="role_add'+count+'" >'
									+ '<td style="height: 30px;">'
									+ roleName
									+ '</td>'
									+ '<td style="height: 30px;"> <center>'
									+ '<span title="ลบข้อมูล">'
									+ '<input type="image" src="image/delete_icon.png" height="30px" width="30px" onclick="delete_role('+count+')" />'
									+ '</span>'
									+ '</center> </td>'
									+ '</tr>';
						
						$('#table_role_add').append(text);
						
						var elem = document.getElementById("num_role");
						elem.value = count;
					}
					else {
						alert("หน้าที่นี้เลือกไปแล้วค่ะ");
					}
				}
					
			});
			
			$('#save').click(function(){
				
				if(checkUsername) {
					alert("กรุณาตรวจสอบชื่อผู้ใช้งานก่อนค่ะ");
				}
				else {
						var check_error = "";

						var salt = document.getElementById("salts").value;
						var fullname = document.getElementById("name").value;
						var name_temp = fullname.split(" ");
						var name = "";
						var surname = "";
						
						//alert("name_temp ln "+name_temp.length);//////////////////////////////////////
						
						if(name_temp.length == 2) {
							name = fullname.substr(0,fullname.indexOf(' '));
							if(/^[@#$%^&*()-_+=!<>]*$/.test(name) == true) { 
								
								//alert("name");///////////////////////////////////////////////
								
								check_error = check_error + " ชื่อ";
							}
							surname = fullname.substr(fullname.indexOf(' ')+1).trim();
							if(/^[@#$%^&*()-_+=!]*$/.test(surname) == true) { 
								
								//alert("surname");///////////////////////////////////////////////
								
								check_error = check_error + " นามสกุล";
							}
						}
						else {
							check_error = check_error + " ชื่อและนามสกุล";
						}
						
						var username = document.getElementById("username").value;
						var password = document.getElementById("password").value;
						var passwordRe = document.getElementById("passwordRe").value;
						
						
						
						var select = document.getElementById("workgroup");
						var workgroup = select.options[select.selectedIndex].value;
						if(workgroup == "select") {
							check_error = check_error + " หน่วยงาน";
						}
						
						var select2 = document.getElementById("status");
						var status = select2.options[select2.selectedIndex].value;
						if(status == "select") {
							check_error = check_error + " สถานะ";
						}
						
						var startDate = document.getElementById("startDate").value;
						if(!startDate) {
							check_error = check_error + " วันเริ่มต้นใช้งาน";
						}
						
						var check_endDate = true;
						var endDate = document.getElementById("endDate").value;
						if(!endDate) {
							check_endDate = false;
						}
						
						var num_role = document.getElementById("num_role").value;
						if(num_role == 0) {
							check_error = check_error + " หน้าที่";
						}
						
						//alert("check_error  "+check_error);//////////////////////////////////////////////
						
						if(check_error != "") {
							alert("กรุณาเลือก"+check_error+" ก่อนค่ะ");
						}
						else {							
							// check password and re password are same
							if(password != passwordRe) {
								alert("password และ repassword ไม่ตรงกัน กรุณากรอกใหม่อีกครั้งค่ะ");
							}
							else {	
								/* AJAX */
								var xmlhttp;
								
								if(window.XMLHttpRequest) {
									// code for IE7+, Firefox, Chrome, Opera, Safari
									xmlhttp = new XMLHttpRequest();
								}
								else {
									// code for IE6, IE5
									xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
								}
								
								xmlhttp.onreadystatechange = function() {
									if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
										var result = xmlhttp.responseText.trim();
										if(result == "Success"){
											alert("บันทึกข้อมูลสำเร็จ");
											document.location.href = "admin_account.jsp";
										}else if(result == "Failed"){
											alert("บันทึกข้อมูลผิดพลาด กรุณาลองใหม่อีกครั้ง");
											document.location.href = "admin_account.jsp";
										}else if(result == "Special"){
											alert("กรุณาใส่ตัวอักษรหรือตัวเลขเท่านั้น");
											document.location.href = "admin_account.jsp";
										}else if(result == "Noname"){
											alert("ไม่มีชื่อบุคคลนี้อยู่ในระบบค่ะ");
											//document.location.href = "admin_account.jsp";
										}
										
										
									}
								}
								//alert(num_role);
								var parameter = "name="+name+"&surname="+surname+"&username="+username+"&password="+password+"&workgroup="+workgroup
												+"&status="+status+"&startDate="+startDate+"&numRole="+num_role+"&salt="+salt;
								// add parameter end date
								if(check_endDate) {
									parameter = parameter + "&endDate='"+endDate+"'";							
								}	
								else {
									parameter = parameter + "&endDate=null";
								}
								// add parameter role							
								for(i=0; i<num_role; i++) {
									var role = document.getElementById("roleId_add"+(i+1)).value;
									parameter = parameter + "&role"+(i+1)+"="+role;
								}
								
								alert(parameter);//////////////try////////////
								
								xmlhttp.open("POST", "admin_account_add_save.jsp?"+parameter, true);
								xmlhttp.send();
						}
						
					}				
				}
				
			});	
			
		});		
		
		function delete_role(roleId) {				
			$('#role_add'+roleId).remove();
			$('#roleId_add'+roleId).remove();
			$('#roleName'+roleId).remove();


			for(var i=count; i>roleId; i--) {				
				var role_add = document.getElementById("role_add"+i);
				role_add.id = "role_add"+(i-1);  // using element properties
				role_add.setAttribute("name", "role_add"+(i-1));  // using .setAttribute() method
				
				var roleId_add = document.getElementById("roleId_add"+i);
				roleId_add.id = "roleId_add"+(i-1);  // using element properties
				roleId_add.setAttribute("name", "roleId_add"+(i-1));  // using .setAttribute() method
				
				var roleName = document.getElementById("roleName"+i);
				roleName.id = "roleName"+(i-1);  // using element properties
				roleName.setAttribute("name", "roleName"+(i-1));  // using .setAttribute() method
				
			}
			
			count--;
			
			if(count == 0) {
				$('#table_role_add').hide();
			}
			
			var elem = document.getElementById("num_role");
			elem.value = count;

		}

		
		function check_username() {
			var username = document.getElementById("username").value;
			var text_error = "";
			
			if(username.indexOf(' ') >= 0) {
				text_error = text_error + "ห้ามมีช่องว่าง";
			}
			if(username.length < 5 || username.length > 20) {
				text_error = text_error + " ต้องมีความยาว 5-20 ตัวอักษรค่ะ";
			}
			if(/^[a-zA-Z0-9 ]*$/.test(username) == false) { // [a-zA-Z0-9- ]
				text_error = text_error + "  เป็นได้แค่ a-z, A-Z และ 0-9 เท่านั้นค่ะ";
			}
			
			if(text_error != "") {
				alert("ชื่อผูใช้"+text_error);
			}
			else {
				// check username has in DB
				/* AJAX */
				var xmlhttp;
				
				if(window.XMLHttpRequest) {
					// code for IE7+, Firefox, Chrome, Opera, Safari
					xmlhttp = new XMLHttpRequest();
				}
				else {
					// code for IE6, IE5
					xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
				}
				
				xmlhttp.onreadystatechange = function() {
					if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
						var result = xmlhttp.responseText;
						
						if(result == "success") {
							alert("ชื่อผูใช้ " +username+ " สามารถใช้ได้ค่ะ");
							$('#checkUsername').hide();
							
							$('#username').prop('readonly', true);
							checkUsername = false;
						}
						else if(result == "fail") {
							alert("ชื่อผูใช้ " +username+ " มีคนใช้ได้ค่ะ");
						} 
					}
				}
				
				xmlhttp.open("POST", "admin_account_check_username.jsp?username="+username, true);
				xmlhttp.send();
				
			}
		}
		
		function search_name(name) {	
			if($('#namelist').find('option').length > 0) {
				
				$('#namelist').find('option').remove();
			}
			if(name != "") {
				/* AJAX */
				var xmlhttp;
				
				if(window.XMLHttpRequest) {
					// code for IE7+, Firefox, Chrome, Opera, Safari
					xmlhttp = new XMLHttpRequest();
				}
				else {
					// code for IE6, IE5
					xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
				}
				
				xmlhttp.onreadystatechange = function() {
					if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {						
						var jsonObj = JSON.parse(xmlhttp.responseText);
						
						if(jsonObj.length == 0) {
							// no data
						}
						else{
							for(i in jsonObj) {
								var text = jsonObj[i].nameTH+" "+jsonObj[i].surnameTH;
								var option = '<option value="'+text+'" >';
								
								$('#namelist').append(option);
							}
						}
					}
				}
				
				xmlhttp.open("POST", "search_name_lec_emp.jsp?name="+name, true);
				xmlhttp.send();
			}			
		}
		
	</script>
</head>
<body>

<%
	//get session
	String strUser = String.valueOf(session.getAttribute("sUser"));
	HttpSession htp_session = request.getSession();
	
	// check session
		if (htp_session == null || htp_session.getAttribute("sUser") == null) {
		    // Forward the control to login.jsp if authentication fails or session expires
		    request.getRequestDispatcher("/login.jsp").forward(request,
		        response);
		}
		if(!"admin".equals(htp_session.getAttribute("sUser"))){%>
			<script>alert("This user dont have PERMISSION to access this zone.");</script>
			<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=system_select.jsp"> 	
	<%}
	
	//set Database Connection
	String hostProps = "";
	String usernameProps  = "";
	String passwordProps  = "";
	String databaseProps = "";
	
	try {
		//get current path
		ServletContext servletContext = request.getSession().getServletContext();
		
		InputStream input = servletContext.getResourceAsStream("/properties/connectDB.properties");
		Properties props = new Properties();
		
		props.load(input);

		hostProps  = props.getProperty("host");
		usernameProps  = props.getProperty("username");
		passwordProps  = props.getProperty("password");
		databaseProps = props.getProperty("database");
	} catch (Exception e) { 
		out.println(e);  
	}

	// connect database
	Connection connect = null;		
	try {
		Class.forName("com.mysql.jdbc.Driver");
	
		connect =  DriverManager.getConnection("jdbc:mysql://" + hostProps  + "/" + databaseProps +
				"?user=" + usernameProps  + "&password=" + passwordProps + "&characterEncoding=tis620");//////"&characterEncoding=tis620" Encoding Thai);
	
		if(connect != null){
			System.out.println("Database Connect Sucesses.");
		} else {
			System.out.println("Database Connect Failed.");	
		}

	} catch (Exception e) {
		out.println(e.getMessage());
		e.printStackTrace();
	}
	
	/* find role in database */
	List<Role> role = new ArrayList<Role>();
	
	try {			   
		ResultSet rs = connect.createStatement().executeQuery("SELECT role_id, role_name, permission, R.system_id, system_name, system_name_th " 
				+ " FROM role R, system S " 
				+ " WHERE R.system_id=S.system_id "
				+ " ORDER BY role_name");
		
		while(rs.next()) {
			Role rol = new Role();
			
			rol.setRoleId(rs.getInt("role_id"));
			rol.setRoleName(rs.getString("role_name"));
			rol.setPermission(rs.getString("permission"));
			rol.setSystemId(rs.getInt("system_id"));
			rol.setSystemName(rs.getString("system_name"));
			rol.setSystemNameTH(rs.getString("system_name_th"));
			
			role.add(rol);
		}
		
	} catch (SQLException e) {
		e.printStackTrace();
	}
	
	// find workgroup in database
	List<Workgroup> workgroup = new ArrayList<Workgroup>();
	
	try {			   
		ResultSet rs = connect.createStatement().executeQuery("SELECT workgroup_name, workgroup_id " 
				+ " FROM  workgroup " 
				+ " ORDER BY  workgroup_name");
		
		while(rs.next()) {
			Workgroup work = new Workgroup();
			
			work.setWorkgroupId(rs.getInt("workgroup_id"));
			work.setWorkgroupName(rs.getString("workgroup_name"));
			
			workgroup.add(work);
		}
		
	} catch (SQLException e) {
		e.printStackTrace();
	}
	
	connect.close();
	
%>

	<div id="page-wrap">
			<div id="inside">
				<table border="0">
					<tr style="font-size:24px">
						<td width="600" height="100" style= "background-color: #273b80;border: 0px ;padding: 0px; 0px;" >
							<div id="header_banner-2"></div>
						</td>
						
						<td width="680" height="100" style= "background-color: #273b80;border: 0px;padding: 0px; 0px;" >
							<p align="right"><label><font size="4" color="#ffffff">username : <%=strUser%>&nbsp;&nbsp;</font></label></p>
							<a href="logout.jsp"><p align="right"><label><font size="3" color="#ffffff">log out &nbsp;</font></label></p></a>
						</td>
					</tr>
				</table>
						<div id="main-content-ac">
        					
							<div class="imageFrame">เพิ่มบัญชีผู้ใช้</div>
							
							<br/><br/><br/><br/><br/><br/>
        					
        					<center>
        					<table width="800" border="0">
        						<form id="form1" name="form1" method="post" action="">
						       		<tr style="font-size:24px">
						           	  <td width="400" height="50">
						                	<font size="5"><strong>ชื่อ</strong></font>
						                	<label><font size="5" color="#FF0000">*</font></label>
						                </td>
						                <td width="400" height="50">
						                	<input type="text" name="name" id="name" value="" list="namelist" autocomplete="off" onkeyup="search_name(this.value)" required />
						                	<datalist id="namelist">
											</datalist>
						                	
						                </td>
						            </tr>
						            
						            <tr style="font-size:24px">
						            	<td width="400" height="50">
						                	<font size="5"><strong>ชื่อผู้ใช้งาน</strong></font>
						                	<label><font size="5" color="#FF0000">*</font></label>
						                </td>
						                <td width="400" height="50">
						                	<input type="text" name="username" id="username" required maxlength="16"/>
						                	&nbsp;&nbsp;
						                	<input type="button" name="checkUsername" id="checkUsername" value="ตรวจสอบ" onclick="check_username()" />
						                </td>
						            </tr>
						            
						            <tr style="font-size:24px">
						            	<td width="400" height="50">
						                	<font size="5"><strong>รหัสผ่าน</strong></font>
						                	<label><font size="5" color="#FF0000">*</font></label>
						                	
						                </td>
						                <td width="400" height="50">
						                	<input type="password" name="password" id="password" required />
						                </td>
						            </tr>
						            
						            <tr style="font-size:24px">
						            	<td width="400" height="50">
						                	<font size="5"><strong>ยืนยันรหัสผ่าน</strong></font>
						                	<label><font size="5" color="#FF0000">*</font></label>
						                	
						                </td>
						                <td width="400" height="50">
						                	<input type="password" name="passwordRe" id="passwordRe" required />
						                </td>
						            </tr>
						            
						            <tr style="font-size:24px">
						            	<td width="400" height="50">
						                	<font size="5"><strong>หน่วยงาน</strong></font>
						                	<label><font size="5" color="#FF0000">*</font></label>
						                </td>
						                <td width="400" height="50">
						                	<select id="workgroup" required >
												<option value="">เลือก</option>
<%
						for(Workgroup wg : workgroup) {

%> 
												<option value="<%=wg.getWorkgroupId()%>"> <%=wg.getWorkgroupName() %> </option>
<%
						}

%> 											</select>
						                	
						                </td>
						            </tr>
						            
						            <tr style="font-size:24px">
						            	<td width="400" height="50">
						                	<font size="5"><strong>สถานะ</strong></font>
						                	<label><font size="5" color="#FF0000">*</font></label>
						                </td>
						                <td width="400" height="50">
						                	<select name="status" id="status" required>
												<option value="select">Select</option>
												<option value="1">Active</option>
												<option value="0">Inactive</option>
											</select>
											
						                </td>
						            </tr>
						            
						            <tr style="font-size:24px">
						            	<td width="400" height="50">
						                	<font size="5"><strong>วันที่เริ่มต้นใช้งาน</strong></font>
						                	<label><font size="5" color="#FF0000">*</font></label>
						                </td>
						                <td width="400" height="50">
						                	<input type="date" name="startDate" id="startDate" required>
						                </td>
						            </tr>
						            
						            <tr style="font-size:24px">
						            	<td width="400" height="50">
						                	<font size="5"><strong>วันที่สิ้นสุดการใช้งาน</strong></font>
						                </td>
						                <td width="400" height="50">
						                	<input type="date" name="endDate" id="endDate"> 
						                </td>
						            </tr>
						           
						             <tr style="font-size:24px">
						            	<td width="400" height="50">
						                	<font size="5"><strong>หน้าที่</strong></font>
						                	<label><font size="5" color="#FF0000">*</font></label>
						                </td>
						                <td width="400" height="50">
						                	<select name="role" id="role" required>
						                        <option value="select">เลือก</option>
<%
								for(int i=0; i<role.size(); i++) {
%>
												<option value="<%=role.get(i).getRoleId()%>"> <%=role.get(i).getRoleName() %> </option>
<%	
								}									
%>						                	
											</select>
											&nbsp;&nbsp;
						                	<input type="button" name="add" id="add" value="add" style="width: 50px; height: 30px;"/>
						                </td>
						            </tr>
						          
						            <tr style="font-size:24px">
						            	<td width="400" colspan="2">
						            	
						                	<center>
							                	<table width="500" id="table_role_add" name="table_role_add">
							                		<tr>
								                		<td style="text-align: center; height: 30px;">
								                			ชื่อหน้าที่
								                		</td>
								                		
								                		<td style="height: 30px;">
								                		</td>
								                	</tr>
								                	<input type="hidden" id="num_role" name="num_role" value="0" />
							                	</table>
						                	</center>
						                	
						                </td>
						            </tr>
						            
						            <tr>
						            	<td colspan="2">
						            		<label><font size="3" color="#FF0000">หมายเหตุ: * คือ ข้อมูลสำคัญ จำเป็นต้องกรอก</font></label>
						            	</td>
						            </tr>
						            
						             <tr style="font-size:24px">
						             <%
////////////////////////////////GEN SALT//////////////////////////////////////////////////////
						             	SaltGen saltz = new SaltGen();
						             	String salt = saltz.genTimeStamp();
						             	System.out.println("salt: "+salt);
						             %>
						             <input type="hidden" id="salts" name="salts" value="<%=salt %>" />
						            	<td width="400" height="50">
						                	<center><input type="button" name="save" id="save"  value="save" class="buttonStyle"/></center>
						                </td>
						        </form>						           
						                <td width="400" height="50">
						                	<center><a href="admin_account.jsp"><button class="buttonStyle">cancel</button></a></center>
						                </td>
					            	</tr>
					       </table>
						</center>
						
						<br><br><br>
						
			<div style="clear: both;"></div>
				
			<div id="footer"></div>
			
		</div>		
			<div style="clear: both;"></div>		
   </div>

</body>
</html>